package com.crazybytex.fragment.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author 本文作者 程序员潇然 疯狂的字节X https://www.crazybytex.com/
 * @Date 2022/10/10 14:41
 * @Description TODO
 **/
public class Client {
    public static void main(String[] args) throws IOException {
        //1.打开通道
        SocketChannel socketChannel = SocketChannel.open();

        //2.设置连接IP和端口号
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));

        //3.写数据
        socketChannel.write(ByteBuffer.wrap("服务端你好".getBytes(StandardCharsets.UTF_8)));

        //4.读取服务器写回的数据
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(readBuffer);
        System.out.println("服务端返回消息：" + new String(readBuffer.array(), 0, read, StandardCharsets.UTF_8));

        //5.释放资源
        socketChannel.close();


    }

}
